package com.dld.coupon.view;

import java.io.ByteArrayInputStream;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;

import com.constant.net.Constant;
import com.dld.android.net.Param;
import com.dld.android.persistent.SharePersistent;
import com.dld.android.util.LogUtils;
import com.dld.coupon.activity.BaseActivity;
import com.dld.coupon.activity.MyCouponDetail;
import com.dld.coupon.activity.R;
import com.dld.coupon.activity.StoreDetail;
import com.dld.coupon.activity.CityActivity.NotifyChangeObserver;
import com.dld.coupon.util.MapUtil;
import com.dld.coupon.util.StringUtils;
import com.dld.protocol.GroupProtocolHelper;
import com.dld.protocol.ProtocolHelper;
import com.dld.protocol.json.Coupon;
import com.dld.protocol.json.CouponDetail;
import com.dld.protocol.json.PageInfo;
import com.dld.protocol.json.Protocol;
import com.tencent.weibo.utils.Cache;

public class GroupLinearLayout extends ListTab implements MainViewBase,
		NotifyChangeObserver {
	private DownloadListView.DownLoadAdapter adapter;
	private Coupon group = new Coupon();
	Handler handler = new Handler();
	private boolean isFirst = true;
	private AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
		public void onItemClick(AdapterView<?> paramAdapterView,
				View paramView, int paramInt, long paramLong) {
			CouponDetail cdd = (CouponDetail) paramView.getTag();
			Log.v("", "*******************   store detail view"
					+ cdd.getDisid());
			Intent it = new Intent(paramView.getContext(), StoreDetail.class);
			it.putExtra(Constant.CONSTANT_SHOPID, cdd.getShopid());
			it.putExtra("previous_pos", BaseActivity.segmentPosition);
			paramView.getContext().startActivity(it);

		}
	};
	private String lastUrl = "";
	private DownloadListView list;
	LinearLayout noResultView;
	private ProtocolCreator protocolCreator;
	private String keyword;
	private int searchType;
	private int category_code;

	public GroupLinearLayout(Context paramContext,
			AttributeSet paramAttributeSet) {
		super(paramContext, paramAttributeSet);
	}

	private void initRefresh() {
		findViewById(R.id.refresh).setOnClickListener(
				new View.OnClickListener() {
					public void onClick(View paramView) {
						GroupLinearLayout.this.request(true, MapUtil
								.getCityId());
					}
				});
	}

	private void request(boolean paramBoolean, String cityid) {

		try {
			Param param = new Param();
			this.cityId = MapUtil.getCityId();
			Log.v("", "request ***************** " + this.city);

			param.append("areaCode", cityid);
			param.append("userAgent", "dld_android");
			param.append("currentPage", "" + this.pageIndex);

			if (keyword != null) {
				param.append("r", "www/api/search");
				param.append("keyword", keyword);
				param.append("searchType", "" + this.searchType);
			} else {
				param.append("r", "www/api/list");
				param.append("module", "shop");
				if (this.category.code != 100) {
					param.append("categoryCode", "" + this.category.code);
				}
				param.append("viewType", "2");
			}

			if (paramBoolean) {
				for (int i = 0; i < this.pageIndex; i++)
					Cache.remove(this.protocolCreator.createProtocol(
							this.activity, param).getAbsoluteUrl());
				this.pageIndex = 1;
			}
			LogUtils.log("GroupLinearLayout", "false");
			if (this.pageIndex == 1) {
				LogUtils.log("GroupLinearLayout", "group.details.clear");
				this.group.details.clear();
				this.list.reset();
			}
			Protocol localProtocol = this.protocolCreator.createProtocol(
					this.activity, param);
			localProtocol.startTrans(new RecommendProtocolResult(String.class));
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	protected void init() {
		init(this.protocolCreator, null, false, 100);
	}

	protected void init(ProtocolCreator paramProtocolCreator,
			String paramString, boolean paramBoolean, int cat_code) {

		if (paramProtocolCreator != null) {
			this.protocolCreator = paramProtocolCreator;
		} else {
			protocolCreator = new ProtocolCreator() {

				public Protocol createProtocol(Context paramContext, Param param) {
					return new Protocol(param);
				}
			};
		}
		this.city = SharePersistent.getInstance().getPerference(this.activity,
				"city_name");
		this.list = ((DownloadListView) findViewById(R.id.listview));
		this.list.setOnItemClickListener(this.itemClickListener);
		this.adapter = new ListViewAdapter(this.list, this.group,
				Constant.VIEW_STORE);
		this.list.setAdapter(this.adapter);
		initAddressList(paramString, paramBoolean);
		initCategoryList(cat_code);
		initRefresh();
		request();
	}

	public void onChangeCity(String paramString1, String paramString2) {
		if ((this.showing) && (!StringUtils.isEmpty(paramString1))) {
			if (StringUtils.isEmpty(paramString1))
				this.city = paramString1;
			init();
		}
	}

	public void onHide() {
		this.showing = false;
		hideList();
	}

	public void onShow() {
		show(null, null, false, 100, null, 1);
	}

	protected void request() {
		request(false, MapUtil.getCityId());
	}

	public void show(ProtocolCreator paramProtocolCreator, String paramString,
			boolean paramBoolean, int category_code, String keyword,
			int searchtype) {
		this.showing = true;
		this.keyword = keyword;
		this.searchType = searchtype;
		this.category_code = category_code;
		String str = SharePersistent.getInstance().getPerference(this.activity,
				"city_name");
		if (!this.isFirst) {
			if ((StringUtils.isEmpty(this.city)) || (this.city.equals(str))) {
				if (StringUtils.isEmpty(str)) {
					SharePersistent.getInstance().getPerference(this.activity,
							"city_name");
					this.pageIndex = 1;
					request();
				}
			} else
				init(paramProtocolCreator, paramString, paramBoolean,
						category_code);
		} else {
			init(paramProtocolCreator, paramString, paramBoolean, category_code);
			this.isFirst = false;
		}
	}

	private class ListViewAdapter extends GroupDownLoadAdapter {
		public ListViewAdapter(DownloadListView paramGroup, Coupon coupon,
				int view_type) {
			super(paramGroup, coupon, view_type);
		}

		public Context getContext() {
			return GroupLinearLayout.this.activity;
		}

		public void onNotifyDownload() {
			GroupLinearLayout.this.pageIndex = getListCount() / 10 + 1;
			GroupLinearLayout.this.request();
		}
	}

	public static abstract interface ProtocolCreator {
		public abstract Protocol createProtocol(Context paramContext,
				Param param);
	}

	private class RecommendProtocolResult extends Protocol.OnJsonProtocolResult {
		public RecommendProtocolResult(Class cls) {
			super(cls);
		}

		private void notifyNoResult() {
			try {
				GroupLinearLayout.this.handler.post(new Runnable() {
					public void run() {
						GroupLinearLayout.this.adapter.notifyNoResult();
					}
				});
			} catch (Exception localException) {
				LogUtils.e("test", "", localException);
			}
		}

		public void onException(String paramString, Exception paramException) {
			notifyNoResult();
		}

		public void onResult(String paramString, final Object paramObject) {
			GroupLinearLayout.this.activity.runOnUiThread(new Runnable() {
				public void run() {
					try {
						String content = (String) paramObject;
						Element root = DocumentBuilderFactory.newInstance()
								.newDocumentBuilder().parse(
										new ByteArrayInputStream(content
												.getBytes()))
								.getDocumentElement();

						NodeList lsittotal = root.getElementsByTagName("total");
						String total = lsittotal.item(0).getFirstChild()
								.getNodeValue();
						PageInfo pinfo = new PageInfo();
						pinfo.total = Integer.parseInt(total);
						GroupLinearLayout.this.group.pageInfo = pinfo;
						if (pinfo.total != 0) {
							List<CouponDetail> nlist = CouponDetail
									.fromXmlToAdroundInfo(root);
							GroupLinearLayout.this.group.details.addAll(nlist);
							GroupLinearLayout.this.adapter.notifyDownloadBack();
						} else {
							GroupLinearLayout.this.adapter.notifyNoResult();
						}

					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
		}
	}

	@Override
	protected void requestBy(String cityid) {
		request(false, cityid);
	}
}
